<template>
  <div class="search-result">
    <van-list v-model="loading" :finished="finished" :error.sync="error" error-text="加载失败 请点击重试" finished-text="没有更多了" @load="onLoad">
      <van-cell v-for="(article, index) in list" :key="index" :title="article.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js'
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    }
  },
  methods: {
    async onLoad() {
      try {
        // 请求获取数据
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText
        })
        // console.log(data)

        // 将数据添加到数组列表中
        const { results } = data.data
        this.list = [...this.list, ...results]

        // 将本次的loading关闭
        this.loading = false

        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.$toast('数据获取失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
